package org.rvk.vms.dal.model;

import org.rvk.vms.dal.cache.Cacheable;
import org.rvk.vms.dal.cache.State;

import java.io.Serializable;
import java.util.Map;
import java.util.Set;

/**
 * The model to hold volunteers summary on Volunteers dashboard.
 *
 * @author Ashish Kumar Sinha <aksinha.mail@gmail.com>
 */
public class VolunteersSummary implements Cacheable, Serializable {

    private long lastUpdateTime;
    private final long AGE_IN_MILLIS = 6 * 3600 * 1000;

    private int totalVolunteers;
    private Map<State, Integer> mapAllStatesVolunteersCount;

    public long getLastUpdateTime() {
        return lastUpdateTime;
    }

    public int getTotalVolunteers() {
        return totalVolunteers;
    }

    public Map<State, Integer> getMapAllStatesVolunteersCount() {
        return mapAllStatesVolunteersCount;
    }

    /**
     * To set the state vise count of all volunteers. The setter also sets the values of other related data viz.
     * #lastUpdateTime  and #totalVolunteers . These data can not be set explicitly.
     *
     * Also note that the map must contain volunteers count for existing states in the database. For missing state
     * information "State.NA" should be used.
     *
     * @param mapAllStatesVolunteersCount
     */
    public void setMapAllStatesVolunteersCount(Map<State, Integer> mapAllStatesVolunteersCount) {
        if(mapAllStatesVolunteersCount == null || mapAllStatesVolunteersCount.isEmpty()){
            return;
        }
        this.mapAllStatesVolunteersCount = mapAllStatesVolunteersCount;
        // also set current time
        this.lastUpdateTime = System.currentTimeMillis();
        Set<State> keySet = mapAllStatesVolunteersCount.keySet();

        int total = 0;

        for (State key : keySet){
            if(mapAllStatesVolunteersCount.get(key) != null) {
                total = total + mapAllStatesVolunteersCount.get(key).intValue();
            }
        }
        this.totalVolunteers = total;
    }

    /**
     * To get the last update time in Millis. A negative value means the cache is always valid and update is not required.
     *
     * @return - last update time milli second. Returns a negative value if the update is not required.
     */
    @Override
    public long getLastUpdateTimeInMillis() {
        return lastUpdateTime;
    }

    /**
     * Defines the age of the cacheable data in milli seconds.
     * A negative value means the cache is always valid and update is not required.
     *
     * @return - the age of the cacheable data in millis. Returns a negative value if the update is not required.
     */
    @Override
    public long ageInMillis() {
        return AGE_IN_MILLIS;
    }
}
